﻿using System.Windows;
using VM.CameraSet;
using VM.Common.Enums;
using VM.Dialogs.Views;
using VM.Start.Common.Provide;
using VM.Start.Core;
using VM.Start.Services;

namespace VM.Start.Methods
{

    public struct TemplateMatchingData
    {
        public bool Flag; // 标志
        public float X; // X 坐标
        public float Y; // Y 坐标
        public float Angle; // 角度
        public string TemplateName; // 模板名称
    }

    public class VisionOperator
    {
        private const string TemplateMatchingPluginName = "模板匹配"; // 模板匹配插件名称
        private const string StatusKey = "状态"; // 状态键
        private const string CenterXKey = "匹配框中心X"; // 匹配框中心X键
        private const string CenterYKey = "匹配框中心Y"; // 匹配框中心Y键
        private const string AngleKey = "匹配框角度"; // 匹配框角度键

        public static void CreateTemplate(string? modelName = null)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 检查 Solution 和 CurrentProject 是否为 null
                if (Solution.Ins == null || Solution.Ins.CurrentProject == null)
                {
                    MessageView.Ins.MessageBoxShow("当前项目未加载！！", eMsgType.Error);
                    return;
                }

                // 检查当前流程是否包含模块
                if (Solution.Ins.CurrentProject.ModuleList == null || Solution.Ins.CurrentProject.ModuleList.Count == 0)
                {
                    MessageView.Ins.MessageBoxShow("当前流程没有模块！", eMsgType.Error);
                    return;
                }

                // 初始化模块并显示
                if (!string.IsNullOrEmpty(modelName))
                {
                    var targetModule = Solution.Ins.CurrentProject.GetModuleByName(modelName);
                    if (targetModule == null)
                    {
                        MessageView.Ins.MessageBoxShow($"未找到指定模块：{modelName}！", eMsgType.Error);
                        return;
                    }

                    InitializeAndShowModule(targetModule);
                }
                else
                {
                    // 遍历模块列表，查找匹配的模板模块
                    foreach (var module in Solution.Ins.CurrentProject.ModuleList)
                    {
                        if (module.ModuleParam.PluginName == TemplateMatchingPluginName)
                        {
                            InitializeAndShowModule(module);
                            return;
                        }
                    }
                    MessageView.Ins.MessageBoxShow("未找到模板匹配模块！", eMsgType.Error);
                }
            });
        }

        // 抽取模块初始化和显示逻辑
        private static void InitializeAndShowModule(ModuleBase module)
        {
            if (module.ModuleView == null)
            {
                try
                {
                    var pluginInfo = PluginService.PluginDic_Module[module.ModuleParam.PluginName];
                    module.ModuleView = (ModuleViewBase)Activator.CreateInstance(pluginInfo.ModuleViewType);
                    module.ModuleView.ModuleBase = module;
                }
                catch (Exception ex)
                {
                    MessageView.Ins.MessageBoxShow($"模块视图初始化失败：{ex.Message}", eMsgType.Error);
                    return;
                }
            }

            module.SetDefaultLink();
            module.ModuleView.ShowModule();
        }

        public static void CameraCaptureSingle()
        {
            CameraSetViewModel.Ins.ButtonOperateCommand.Execute("SingleAcq");
        }

        public static void CameraCapture(bool flag)
        {
            if (CameraSetViewModel.Ins.ButtonContent == "连续采集" && flag)
            {
                // 触发连续采集操作
                CameraSetViewModel.Ins.ButtonOperateCommand.Execute("ContinuousAcq");
            }

            if (CameraSetViewModel.Ins.ButtonContent == "停止采集" && !flag)
            {
                // 触发连续采集操作
                CameraSetViewModel.Ins.ButtonOperateCommand.Execute("ContinuousAcq");
            }
        }


        public static TemplateMatchingData GetPoint(string? templateName = null)
        {
            CameraCapture(false);
            TemplateMatchingData matchingData = new TemplateMatchingData
            {
                Flag = false
            };

            Application.Current.Dispatcher.Invoke(() =>
            {
                try
                {
                    // 查找模板匹配模块并确保只有一个模板匹配模块
                    var matchModules = Solution.Ins.CurrentProject.ModuleList
                        .Where(module => module.ModuleParam.PluginName == TemplateMatchingPluginName)
                        .ToList();

                    // 检查模板匹配模块数量
                    if (matchModules.Count == 0)
                    {
                        MessageView.Ins.MessageBoxShow("当前流程没有模板匹配模块！", eMsgType.Error);
                        return;
                    }
                    else if (matchModules.Count > 1)
                    {
                        MessageView.Ins.MessageBoxShow("当前流程有多个模板匹配模块！", eMsgType.Error);
                        return;
                    }

                    // 获取唯一的模板匹配模块
                    var matchModule = matchModules.First();

                    // 执行指定模板的多模块
                    Solution.Ins.CurrentProject.ExcuteMultiModuleByName("", templateName);

                    // 获取 SelectedTemplate 属性的值
                    var selectedTemplateValue = GetPropertyValue(matchModule, "SelectedTemplate");
                    if (selectedTemplateValue == null)
                    {
                        MessageView.Ins.MessageBoxShow("模板匹配模块的 SelectedTemplate 为空！", eMsgType.Error);
                        return;
                    }

                    // 获取 SelectedTemplate 的 Name 属性
                    var nameValue = GetPropertyValue(selectedTemplateValue, "Name")?.ToString();
                    matchingData.TemplateName = nameValue;

                    // 获取结果数据
                    if (Solution.Ins.CurrentProject.OutputMap.TryGetValue(matchModule.ModuleParam.ModuleName, out var result))
                    {
                        matchingData.Flag = Convert.ToBoolean(result[StatusKey].Value);
                        matchingData.X = Convert.ToSingle(result[CenterXKey].Value);
                        matchingData.Y = Convert.ToSingle(result[CenterYKey].Value);
                        matchingData.Angle = Convert.ToSingle(result[AngleKey].Value);

                    }
                    else
                    {
                        MessageView.Ins.MessageBoxShow("未找到匹配模块的输出结果！", eMsgType.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageView.Ins.MessageBoxShow($"发生错误: {ex.Message}", eMsgType.Error);
                }
            });
            Logger.AddLog(
                        $"匹配点位X坐标为{matchingData.X},Y坐标为[{matchingData.Y}]");

            return matchingData;
        }

        private static object? GetPropertyValue(object obj, string propertyName)
        {
            if (obj == null) return null;
            var property = obj.GetType().GetProperty(propertyName);
            return property?.GetValue(obj);
        }

        // 通用方法：通过反射获取属性值
        private static object? GetPropertyValueByReflection(string pluginName, string propertyName)
        {
            if (PluginService.PluginDic_Module.TryGetValue(pluginName, out var pluginInfo))
            {
                var instance = Activator.CreateInstance(pluginInfo.ModuleType);
                return GetPropertyValue(instance, propertyName);
            }
            return null;
        }
    }

}
